package com.maochd.platform.domain;

import com.maochd.platform.constant.DingTalkConstants;
import com.maochd.platform.util.TemplateUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import one.util.streamex.StreamEx;

import java.util.List;

/**
 * 钉钉消息构建实体类
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Msg2DingTalk {

    /**
     * 项目名称
     */
    private String projectName;

    /**
     * 分支名称
     */
    private String branch;

    /**
     * 构建状态
     */
    private String status;

    /**
     * 触发人
     */
    private String triggered;

    /**
     * 执行机器
     */
    private String agent;

    /**
     * 详情链接
     */
    private String detail;

    /**
     * 构建钉钉消息
     *
     * @param robotName 机器人名称
     * @param template  模板
     * @return 钉钉消息实体
     */
    public DingTalk dtBuild(String robotName, String template) {
        DingTalk dt = new DingTalk();
        dt.setRobotName(robotName);
        dt.setMsgtype("markdown");
        DingTalk.MarkDown markDown = new DingTalk.MarkDown();
        markDown.setTitle("构建通知");
        List<String> mobileList = DingTalkConstants.MOBILE_MAP.get(this.projectName);
        String mobileStr = StreamEx.of(mobileList)
                .map(m -> "@" + m)
                .joining(" ");
        String statusColor = DingTalkConstants.STATUS_COLOR_MAP.get(this.getStatus());
        String text = String.format(TemplateUtils.loadTemplate(template),
                this.projectName, this.branch, statusColor, this.getStatus(),
                this.getTriggered(), this.getAgent(), this.getDetail(), mobileStr);
        markDown.setText(text);
        DingTalk.At at = new DingTalk.At();
        at.setIsAtAll(Boolean.FALSE);
        at.setAtMobiles(mobileList);
        dt.setAt(at);
        dt.setMarkdown(markDown);
        return dt;
    }
}
